<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function updateDOM() {
        console.log("更新视图");
      }

      function isObject(obj) {
        return typeof obj === "object" && obj !== null;
      }

      function reactive(data) {
        return new Proxy(data, {
          get(target, property) {
            const nowData = Reflect.get(target, property);
            if (isObject(nowData)) {
              return reactive(nowData);
            }
            return nowData;
          },
          set(target, property, value) {
            updateDOM();
            return Reflect.set(target, property, value);
          },
          deleteProperty(target, property) {
            updateDOM();
            return Reflect.deleteProperty(target, property);
          },
        });
      }

      //原始数据
      const data = {
        name: "laowang",
        age: 18,
        sex: "女",
        hobby: ["唱", "跳"],
        score: {
          math: 90,
          ch: 100,
        },
      };
      //得到一个代理对象
      const proxyData = reactive(data);

      //获取
      console.log(proxyData.name);

      //设置
      // proxyData.age = 19;
      proxyData.hobby.push("rap");

      //删除
      // delete proxyData.sex;

      //查看深层次也是代理对象
      console.log(proxyData.score);
    </script>
  </body>
</html>
